package com.beagle.njddapp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.beagle.njddapp.R;
import com.beagle.njddapp.base.ApiService;
import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.base.NjOwnerApiService;
import com.beagle.njddapp.base.RetrofitHttp;
import com.beagle.njddapp.bean.MessageBean;
import com.beagle.njddapp.bean.UserInfoBean;
import com.beagle.njddapp.core.LocationManager;
import com.beagle.njddapp.core.LocationUploadService;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.net.BaseHttpResponse;
import com.beagle.njddapp.net.BaseOilHttpListResponse;
import com.beagle.njddapp.net.HttpResponseObserver;
import com.beagle.njddapp.net.RxSchedulers;
import com.beagle.njddapp.ui.activity.owner.MessageActivity;
import com.beagle.njddapp.ui.fragment.CommonMapfragment;
import com.beagle.njddapp.utils.GpsUtil;
import com.beagle.njddapp.utils.PrefsManager;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import okhttp3.RequestBody;

import static com.beagle.njddapp.core.UserService.ROLE;
import static com.beagle.njddapp.core.UserService.ROLE_DIRVER;
import static com.beagle.njddapp.core.UserService.ROLE_OWNER;

/**
 * @author hxx
 * @date 2021-03-31 19:21
 */
public class NewStartActivity  extends AppCompatActivity implements AMapLocationListener, View.OnClickListener {

//    private AMapLocationClient mlocationClient;
//    private AMapLocationClientOption mLocationOption;
    private Intent intent;
    private TextView tvAddress;
    private RelativeLayout container;
    private TextView tvLocation;
    private int type;
    private TextView tvMessage;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_new);
        intent=new Intent(this, LocationUploadService.class);
        StatusBarUtil.darkMode(this);
        tvAddress = findViewById(R.id.tv_address);
        ImageView ivMy = findViewById(R.id.iv_home);
        ivMy.setOnClickListener(this);
        ImageView ivMessage = findViewById(R.id.iv_message);
        ivMessage.setOnClickListener(this);
        tvLocation=findViewById(R.id.tv_location);
        container = findViewById(R.id.home_container);
        StatusBarUtil.setPaddingSmart(this, container);
        tvMessage=findViewById(R.id.tv_meeeage);
        StatusBarUtil.immersive(this);
        tvLocation.setOnClickListener(this);
        TextView tv1=findViewById(R.id.tv1);
        TextView tv2=findViewById(R.id.tv2);
        TextView tv3=findViewById(R.id.tv3);
        TextView tv4=findViewById(R.id.tv4);
        TextView tv5=findViewById(R.id.tv5);
        TextView tv6=findViewById(R.id.tv6);
        TextView tv7=findViewById(R.id.tv7);
        TextView tv8=findViewById(R.id.tv8);
        ImageView iv1=findViewById(R.id.iv1);
        ImageView iv2=findViewById(R.id.iv2);
        RelativeLayout rl=findViewById(R.id.container);
        rl.setOnClickListener(this);
        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
        tv3.setOnClickListener(this);
        tv4.setOnClickListener(this);
        tv5.setOnClickListener(this);
        tv6.setOnClickListener(this);
        tv7.setOnClickListener(this);
        tv8.setOnClickListener(this);
        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
//        startLocation();
        addFragment();
        getNotify();


    }

    public void message(){
        if (UserService.getInstance().getRole() == ROLE_OWNER&&UserService.getInstance().getUserInfoBean()!=null){
            retrofit2.Retrofit retrofit = RetrofitHttp.provideRetrofit();
            //获取接口对象
            NjOwnerApiService apiService = retrofit.create(NjOwnerApiService.class);
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),"{}");
            apiService.message(10+"",1+"",body).compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseOilHttpListResponse<MessageBean>>() {
                @Override
                public void success(BaseOilHttpListResponse<MessageBean> bean) {
                    if (bean!=null&&bean.results!=null){
                        if (bean.unReadCount>0){
                            tvMessage.setText(bean.unReadCount+"");
                            tvMessage.setVisibility(View.VISIBLE);
                        }else {
                            tvMessage.setVisibility(View.GONE);
                        }
                    }else {
                        tvMessage.setVisibility(View.GONE);

                    }
                }

                @Override
                public void error(int code, String message) {
                    tvMessage.setVisibility(View.GONE);

                }
            });
        }else {
            tvMessage.setVisibility(View.GONE);
        }

    }

    private void addFragment() {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        CommonMapfragment commonMapfragment=new CommonMapfragment();
        Bundle bundle=new Bundle();
        bundle.putInt("type",1);
        commonMapfragment.setArguments(bundle);
        transaction.replace(R.id.home_fm_container,commonMapfragment);
        transaction.commitNowAllowingStateLoss();
    }
//    private void startLocation() {
//        if (mlocationClient == null) {
//            mlocationClient = new AMapLocationClient(this);
//            mLocationOption = new AMapLocationClientOption();
//            //设置定位监听
//            mlocationClient.setLocationListener(this);
//            //设置为高精度定位模式
//            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//            //设置定位参数
//            mlocationClient.setLocationOption(mLocationOption);
//            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
//            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
//            // 在定位结束后，在合适的生命周期调用onDestroy()方法
//            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//            mlocationClient.startLocation();
//        }
//    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!GpsUtil.isOPen(getApplicationContext())){
            tvLocation.setVisibility(View.VISIBLE);
        }else {
            tvLocation.setVisibility(View.GONE);
        }
        message();
    }


    @Override
    protected void onDestroy() {
//        super.onDestroy();
//        if (null != mlocationClient) {
//            mlocationClient.onDestroy();
//        }
        stopService(intent);
    }

    private boolean isLocationStart;
    @Override
    public void onLocationChanged(AMapLocation location) {
        if (null != location) {
            LocationManager.getInstance().pubLishLocation(location);
            if (!isLocationStart){
                startService(intent);
                isLocationStart=true;
            }
            StringBuffer sb = new StringBuffer();
            if (location.getErrorCode() == 0) {
                tvAddress.setText(location.getCity());
                sb.append("经    度    : " + location.getLongitude() + "\n");
                sb.append("纬    度    : " + location.getLatitude() + "\n");
            }

            String result = sb.toString();
            LogUtils.d(result);
            LogUtils.d("定位成功:" + location.getErrorCode());
        } else {
            LogUtils.d("定位失败:" + location.getErrorCode());
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl:
                type=4;
                if (UserService.getInstance().getUserInfoBean()==null){
                    realToMain();
                }else {
                    startActivity(new Intent(NewStartActivity.this, MainActivity.class));
                }
                break;
            case R.id.tv1:
                type=3;
                if (UserService.getInstance().getUserInfoBean()==null){
                    realToMain();
                }else {
                    startActivity(new Intent(NewStartActivity.this, MainActivity.class).putExtra("type",1));
                }
                break;
            case R.id.tv2:
            case R.id.tv3:
            case R.id.tv4:
            case R.id.tv5:
            case R.id.tv6:
            case R.id.tv7:
            case R.id.tv8:
            case R.id.iv1:
            case R.id.iv2:
                ToastUtils.showShort("此功能即将开放");
                break;
            case R.id.iv_home:
                type=1;
                if (UserService.getInstance().getUserInfoBean()==null){
                    realToMain();
                }else {
                    startActivity(new Intent(NewStartActivity.this, UserCenterActivity.class));
                }
                break;
            case R.id.iv_message:
                type=2;
                if (UserService.getInstance().getUserInfoBean()==null){
                    realToMain();
                }else {
                    if (UserService.getInstance().getRole()==ROLE_DIRVER){
                        ToastUtils.showShort("此功能即将开放");
                    }else {
                        startActivity(new Intent(this, MessageActivity.class));
                    }
                }
                break;
            case R.id.tv_location:
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent,887);                break;
        }
    }

    public void realToMain(){
        String token = PrefsManager.getInstance(BaseApplication.getInstance()).getString(UserService.TOKEN);
        if (TextUtils.isEmpty(token)) {
            startActivity(new Intent(this, LoginActivity.class));
        } else {
            UserService.getInstance().setToken(token);
            UserService.getInstance().setRole(PrefsManager.getInstance(BaseApplication.getInstance()).getInt(ROLE, 1));
            getUserInfo();
        }
    }

    public void mapToMain(){
        type=4;
        realToMain();
    }
    private void getNotify() {
        NotificationManagerCompat notification = NotificationManagerCompat.from(this);
        boolean isEnabled = notification.areNotificationsEnabled();
        if (!isEnabled) {
            //未打开通知
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("注意")
                    .setMessage("为了更好的服务您，请在设置置中开启允许通知功能")
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent intent = new Intent();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                intent.putExtra("android.provider.extra.APP_PACKAGE", NewStartActivity.this.getPackageName());
                            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {  //5.0
                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                intent.putExtra("app_package", NewStartActivity.this.getPackageName());
                                intent.putExtra("app_uid", NewStartActivity.this.getApplicationInfo().uid);
                                startActivity(intent);
                            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {  //4.4
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setData(Uri.parse("package:" + NewStartActivity.this.getPackageName()));
                            } else if (Build.VERSION.SDK_INT >= 15) {
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                intent.setData(Uri.fromParts("package", NewStartActivity.this.getPackageName(), null));
                            }
                            startActivity(intent);

                        }
                    })
                    .create();
            alertDialog.show();
            alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
        }
    }


    private void getUserInfo() {
        ApiService apiService = RetrofitHttp.provideRetrofit().create(ApiService.class);
        apiService.getUserInfo().compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseHttpResponse<UserInfoBean>>() {
            @Override
            public void success(BaseHttpResponse<UserInfoBean> userInfoBeanBaseHttpResponse) {
                if (userInfoBeanBaseHttpResponse != null && userInfoBeanBaseHttpResponse.data != null) {
                    UserInfoBean infoBean = userInfoBeanBaseHttpResponse.data;
                    UserService.getInstance().setUserInfoBean(userInfoBeanBaseHttpResponse.data);
                    if (0 == infoBean.getUserRole()) {
                        startActivity(new Intent(NewStartActivity.this, ChooseRoleActivity.class));
                    } else if (TextUtils.isEmpty(infoBean.getUserName())) {
                        startActivity(new Intent(NewStartActivity.this, BasicUserInfoActivity.class));
                    } else {
                        if (type==1){
                            startActivity(new Intent(NewStartActivity.this, UserCenterActivity.class));
                        }else if (type==2){
                            if (UserService.getInstance().getRole()==ROLE_DIRVER){
                                ToastUtils.showShort("此功能即将开放");
                            }else {
                                startActivity(new Intent(NewStartActivity.this, MessageActivity.class));
                            }
                        }else if (type==3){
                            startActivity(new Intent(NewStartActivity.this, MainActivity.class).putExtra("type",1));
                        }else {
                            startActivity(new Intent(NewStartActivity.this, MainActivity.class));
                        }
                    }
                } else {
                    startActivity(new Intent(NewStartActivity.this, LoginActivity.class));
                }
            }

            @Override
            public void error(int code, String message) {
                UserService.getInstance().clear();
                startActivity(new Intent(NewStartActivity.this, LoginActivity.class));
            }
        });
    }

    boolean isExit;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    public void exit(){
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            System.exit(0);
        }
    }
}
